package com.indi.gulimall.seckill.listener;

import com.indi.common.constant.SeckillConstant;
import com.indi.common.dto.mq.SeckillSkuDTO;
import com.indi.gulimall.seckill.service.SeckillService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author UnityAlvin
 * @date 2021/7/30 17:43
 */

@RabbitListener(queues = SeckillConstant.SECKILL_RELEASE_STOCK_QUEUE)
@Service
public class SeckillStockListener {
    @Resource
    private SeckillService seckillService;

    /**
     * 释放秒杀订单的库存
     * @param seckillSkuDTO
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleReleaseSeckillStock(SeckillSkuDTO seckillSkuDTO, Message message, Channel channel) throws IOException {
        try {
            System.out.println("收到消息，释放信号量");
            seckillService.releaseStock(seckillSkuDTO);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
